package com.tanhua.manage.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.pojo.Admin;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Au
 * @DATE 2020/11/29 14:54
 **/
@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private AdminMapper adminMapper;

    private static final Logger LOG = LoggerFactory.getLogger(AdminService.class);
    private static final String CACHE_KEY_TOKEN_PREFIX = "MANAGE_TOKEN_";
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String CACHE_CODE_PREFIX = "MANAGE_GAP_";

    public void saveVerification(String uuid, String code) {
        String key = CACHE_CODE_PREFIX + uuid;
        //将验证码保存到redis中，有效时间为5分钟
        this.redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(5));
    }

    public String login(Admin admin, String uuid, String verificationCode) {
        // 校验验证码
        String code = redisTemplate.opsForValue().get(CACHE_CODE_PREFIX + uuid);
        if (!StringUtils.equals(code, verificationCode)) {
            throw new BusinessException("验证码错误");
        }

        // 把原有的验证码删除
        redisTemplate.delete(CACHE_CODE_PREFIX + uuid);

        if (StringUtils.isEmpty(admin.getUsername())) {
            throw new BusinessException("用户名不能为空");
        }
        if (StringUtils.isEmpty(admin.getPassword())) {
            throw new BusinessException("密码不能为空");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", admin.getUsername());
        Admin oneAdmin = adminMapper.selectOne(queryWrapper);

        if (!StringUtils.equals(SecureUtil.md5(admin.getPassword()), oneAdmin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", oneAdmin.getUsername());
        claims.put("id", oneAdmin.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //设置响应数据体
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .compact();

        try {
            // 将token存储到redis中
            String redisTokenKey = CACHE_KEY_TOKEN_PREFIX + token;

            //将密码设置为null，不参与序列化
            oneAdmin.setPassword(null);

            String redisTokenValue = MAPPER.writeValueAsString(oneAdmin);
            this.redisTemplate.opsForValue().set(redisTokenKey, redisTokenValue, Duration.ofDays(7));
            return token;
        } catch (Exception e) {
            LOG.error("存储token出错", e);
            return null;
        }
    }


    /**
     * 根据token从redis中获取用户信息
     */
    public Admin queryUserByToken(String token) {
        try {
            String redisTokenKey = CACHE_KEY_TOKEN_PREFIX + token;
            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);
            if (StrUtil.isEmpty(cacheData)) {
                return null;
            }
            // 刷新时间
            this.redisTemplate.expire(redisTokenKey, 7, TimeUnit.DAYS);
            return MAPPER.readValue(cacheData, Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从redis中删除token缓存
     */
    public void removeToken(String token){
        String redisTokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        this.redisTemplate.delete(redisTokenKey);
    }
}

